'use strict';

const {Controller} = require('egg');
const ResponseUtil = require('../utils/ResponseUtil');

class SysRoleController extends Controller {

    async getRoleList() {
        let query = this.ctx.query;
        query.delFlag = 0;
        const resp = await this.ctx.service.sysrole.selectRoleList(query);
        return this.ctx.body = ResponseUtil.success(resp.list, resp.total);
    }

    async addRole() {
        let body = this.ctx.request.body;
        if (!body.roleName) {
            return ResponseUtil.retArgErr();
        }
        const resp = await this.ctx.service.sysrole.insertRole(body);
        return this.ctx.body = ResponseUtil.success(resp);
    }


    async updateRole() {
        let body = this.ctx.request.body;
        if (!body.roleName || !body.roleKey || !body.roleId) {
            return ResponseUtil.retArgErr();
        }
        const resp = await this.ctx.service.sysrole.updateRole(body);
        return this.ctx.body = ResponseUtil.success(resp);
    }

    async updateRolePerms(){
        let body = this.ctx.request.body;
        const resp = await this.ctx.service.sysrole.updateRolePerms(body);
        return this.ctx.body = ResponseUtil.success(resp);
    }

    async getRoleDetail() {
        let roleId = this.ctx.params.roleId;
        if (!roleId) {
            return ResponseUtil.retArgErr();
        }
        const role = await this.ctx.service.sysrole.selectRoleById(roleId);
        if (null != role) {
            let menuList = await this.ctx.service.sysmenu.getMenuList({});
            const buildMenuList = await this.ctx.service.sysmenu.buildMenuTree(menuList);
            role.menuList = buildMenuList;

            let checkedIdList = await this.ctx.service.sysmenu.selectMenuListByRoleId(roleId);
            role.checkedIdList = checkedIdList;

            role.admin = this.ctx.service.sysrole.isAdmin(role.roleId);
        }
        return this.ctx.body = ResponseUtil.success(role);
    }

    async getRoleListAll() {
        const resp = await this.ctx.service.sysrole.getRoleListAll({status: 0, delFlag: 0});
        return this.ctx.body = ResponseUtil.success(resp);
    }

    async deleteRole() {
        let roleId = this.ctx.params.roleId;
        if (!roleId) {
            return ResponseUtil.retArgErr();
        }
        const resp = await this.ctx.service.sysrole.deleteRoleById(roleId);
        return this.ctx.body = ResponseUtil.success(resp);
    }


}

module.exports = SysRoleController;
